const Proxy = require('../proxy')
const moment = require('moment')
const webDataUtil = require('../util/webDataUtil')
const { numberUtil } = require('../util')

const BtbIndex = Proxy.BtbIndex
const AssetRecordProxy = Proxy.AssetRecord

function parseValue (val) {
  return parseFloat(val || 0) || 0
}

exports.getRecordsByPage = async function (query, paging) {
  // 新创建的在前面
  const opt = {
    skip: paging.start,
    limit: paging.offset,
    sort: '-date'
  }
  const data = await Promise.all([
    AssetRecordProxy.find({}, opt),
    AssetRecordProxy.count({})
  ])
  return { list: data[0], count: data[1] }
}

exports.addAssetRecord = async function () {
  // 12记录
  const nowDate = moment().subtract(1, 'days').format('YYYY-MM-DD')
  const assetList = await AssetRecordProxy.find({
  }, {
    skip: 0,
    limit: 10,
    sort: '-date'
  })
  let lastAsset = assetList[0]
  // 已经有记录了
  if (lastAsset && lastAsset.date === nowDate) {
    return
  }
  const pricesRes = await webDataUtil.binance('getPrices')
  const myPrice = pricesRes.data || {}
  const balanceResXH = await webDataUtil.binance('getBalance')
  const myBalanceXH = balanceResXH.data || {}
  const balanceHY = await webDataUtil.binance('getFuturesAccount')
  const myBalanceHY = balanceHY.data || {}
  const btbList = await BtbIndex.find().select({ code: 1 })

  let usdtSumXH = parseValue(myBalanceXH['USDT'].available)
  let usdtSumHY = parseValue(myBalanceHY.totalMarginBalance)
  btbList.forEach((btbItem) => {
    const usdtKey = `${btbItem.code}USDT`
    const btbBalanceXH = myBalanceXH[btbItem.code]
    if (!btbBalanceXH) {
      return false
    }
    const price = parseValue(myPrice[usdtKey])
    const available = parseValue(btbBalanceXH.available) || 0
    usdtSumXH += (price * available)
  })
  let beforeHY = lastAsset ? lastAsset.hy_usdt : 0
  let beforeXH = lastAsset ? lastAsset.xh_usdt : 0
  await AssetRecordProxy.newAndSave({
    date: nowDate,
    hy_usdt: numberUtil.keepTwoDecimals(usdtSumHY),
    xh_usdt: numberUtil.keepTwoDecimals(usdtSumXH),
    pre_hy_usdt: numberUtil.keepTwoDecimals(beforeHY),
    hy_usdt_diff: numberUtil.keepTwoDecimals(parseValue(usdtSumHY - beforeHY)),
    xh_usdt_diff: numberUtil.keepTwoDecimals(parseValue(usdtSumXH - beforeXH))
  })
}

exports.getAssetRecordsByDay = async function (data) {
  // 新创建的在前面
  const opt = {
    limit: data.day,
    sort: '-date'
  }
  return AssetRecordProxy.find({}, opt)
}

// 获取资产统计
exports.getAssetStatistics = async function () {
  let nowMonth = `${moment().format('YYYY-MM')}-01`
  const nowYear = `${moment().format('YYYY')}-01-01`
  let startRecord = await AssetRecordProxy.find({}, {
    limit: 1,
    sort: 'date'
  })
  startRecord = startRecord[0]
  let lastRecord = await AssetRecordProxy.find({}, {
    limit: 1,
    sort: '-date'
  })
  lastRecord = lastRecord[0]
  // 本月第一天
  let yearRecord = await AssetRecordProxy.find({
    date: {
      $lt: nowYear
    }
  }, {
    sort: '-date',
    limit: 1
  })
  yearRecord = yearRecord[0]
  let monthRecord = await AssetRecordProxy.find({
    date: {
      $lt: nowMonth
    }
  }, {
    sort: '-date',
    limit: 1
  })
  monthRecord = monthRecord[0]
  return {
    startRecord,
    monthRecord,
    yearRecord,
    lastRecord
  }
}

exports.deleteAssetRecords = async function () {
  return AssetRecordProxy.delete({})
}

exports.getAssetRecordDetail = async function (data) {
  return AssetRecordProxy.findOneById(data._id)
}

exports.remarkAssetRecord = async function (data) {
  const newData = {
    ...data
  }
  delete newData._id
  return AssetRecordProxy.update({
    _id: data._id
  }, {
    ...newData
  })
}
